<template>
    <div class="edit-news">
        <h2  class="tit">{{editTt}}</h2>
        <Form ref="formInline" v-if="eduInfo" :model="eduInfo" :rules="eduInfoRules" inline >
            <div class = 'main'>
                <p class="title">基本信息</p>
                <Row class="box">
                    <Col span="16">
                        <div class="address">
                            <i class="req-icon">*</i>标题：
                            <FormItem prop="title" style="width: 85%">
                                <Input
                                    class="w-input"
                                    v-model="eduInfo.title"
                                    type="textarea"
                                    :maxlength="30"
                                    placeholder="输入课堂标题30个汉字以内"
                                />
                            </FormItem>
                        </div>
                    </Col>
                    <Col span="8">
                        <div class="address">
                            <i class="req-icon">*</i>概要/副标题：
                            <FormItem prop="synopsis" style="width: 70%">
                                <Input
                                    class="w-input"
                                    v-model="eduInfo.synopsis"
                                    type="textarea"
                                    :maxlength="50"
                                    placeholder="输入课堂标题50个汉字以内"
                                />
                            </FormItem>
                        </div>
                    </Col>
                    <Col span="8">
                        <div class="address">               
                            <i class="req-icon"></i>栏目：
                            <FormItem prop="type">
                                <Select class="w-select" v-model="eduInfo.type">
                                    <Option
                                        :value="item.id"
                                        v-for="item of tabList"
                                        :key="item.id"
                                    >{{item.name}}</Option>
                                </Select>
                            </FormItem>
                        </div>
                        <div class="address"> 
                            <i class="req-icon"></i>优先级：
                            <FormItem prop="showindex">
                                <!-- <Input
                                    class="w-input"
                                    v-model="eduInfo.showindex"
                                    :maxlength="8"
                                    placeholder="请输入显示序号"
                                    style="width: 120px"
                                /> -->
                                <input min="0" max="9999" v-model="eduInfo.showindex" type="text"  @input="fictitioussrInput" class="inputnumber" placeholder="请输入显示序号"/>
                            </FormItem>
                        </div>
                    </Col>
                    <Col span="8">
                        <div class="address">
                            <i class="req-icon"></i>来源：
                            <FormItem prop="source" style="width: 70%">
                                <Input
                                    class="w-input"
                                    v-model="eduInfo.source"
                                    :maxlength="20"
                                    placeholder="输入标题20个汉字以内"
                                />
                            </FormItem>
                        </div>
                        <div class="address">  
                            <i class="req-icon"></i>状态：
                            <FormItem prop="enable">
                                <Select class="w-select" v-model="eduInfo.enable">
                                    <Option :value="0">禁用</Option>
                                    <Option :value="1">启用</Option>
                                </Select>
                            </FormItem>
                        </div>                    
                    </Col>
                    <Col span="8">
                        <div class="address"> 
                            <i class="req-icon"></i>预设阅读量：
                                <FormItem style="width: 70%">
                                    <!-- <InputNumber v-model.trim="eduInfo.readNum" placeholder="请输入数值" :max="9999999" style="width: 50%"></InputNumber> -->
                                    <input min="0" max="9999999" v-model="eduInfo.readNum" type="text"  @input="readNumInput" class="inputnumber" placeholder="请输入数值"/>
                                </FormItem>
                        </div>
                        <Col span="18">
                            <div class="address"> 
                                <i class="req-icon"></i>列表首页：
                                <FormItem prop="img" >
                                    <span class="avatar-box" v-for="(item,index) of uploadList" :key="index">
                                        <template v-if="item.status === 'finished'">
                                            <Avatar
                                                class="avatar-pic"
                                                shape="square"
                                                icon="ios-person"
                                                :src="item.url"
                                            />
                                            <div class="avatar-img">
                                                <Icon
                                                    type="ios-eye-outline"
                                                    @click.native="handleView(item.url)"
                                                ></Icon>
                                                <Icon
                                                    type="ios-trash-outline"
                                                    @click.native="handleRemove(item)"
                                                ></Icon>
                                            </div>
                                        </template>
                                        <template v-else>
                                            <Progress
                                                v-if="item.showProgress"
                                                class="progress"
                                                :percent="item.percentage"
                                                hide-info
                                            ></Progress>
                                        </template>
                                    </span>
                                    <Upload
                                        v-show="uploadList.length ==0"
                                        ref="upload"
                                        name="file"
                                        :data="jsonObj"
                                        :show-upload-list="false"
                                        :default-file-list="defaultList"
                                        :on-success="handleSuccess"
                                        :format="['jpg','jpeg','png']"
                                        :max-size="maxSize"
                                        :on-format-error="handleFormatError"
                                        :on-exceeded-size="handleMaxSize"
                                        :before-upload="handleBeforeUpload"
                                        :headers="fromData"
                                        type="drag"
                                        :action="uploadUrl"
                                        style="display: inline-block;width:58px;margin-left: 15px"
                                        class="upload-avatar"
                                    >
                                        <div style="width: 64px;height:64px;line-height: 64px;">
                                            <Icon type="ios-camera" size="20"></Icon>
                                        </div>
                                    </Upload>
                                </FormItem>
                            </div>
                        </Col>
                        <!-- <Col span="6">
                            <RadioGroup v-model="eduInfo.pageStyle" size="large">
                                <Radio label="1">方图</Radio>
                                <Radio label="2">长图</Radio>
                            </RadioGroup>
                        </Col> -->
                        <Col span="24">
                            <div style="margin:-20px 0 20px 10px">
                                <small style="color:#ff9966">（备注：图片大小不超过1024kb，建议170*170px）</small>
                            </div>
                        </Col>
                    </Col>
                </Row>
            </div> 
            <div class = 'main'>
                <p class="title">详细内容</p>            
                <Row class="box">
                    <Col span="24">
                        <FormItem prop="content" style="width:100%;">
                            <vueEditor
                                id="healthEditor"
                                :textHtml="eduInfo.content"
                                :urlCode="urlCode"
                                @valueHandle="afterChange"
                                style='width:100%;margin:0'
                            ></vueEditor>
                        </FormItem>
                    </Col>
                </Row>
            </div>            
        </Form> 
        <div class="btn">
            <Button type="primary" @click="submit('formInline')" style='text-align:center;' class="button">
                <Icon type="ios-checkmark" style="margin-right: 5px"/>提交</Button>
            <Button  @click="reback" class="button">
                <i class = "iconfont icon-butongyi" style="font-size:14px;margin-right:5px"></i>返回
            </Button>
        </div>
        <Modal title="大图预览" :footer-hide="true" v-model="visible" :styles="{top: '20px'}">
            <img :src="imgName" v-if="visible" style="width: 100%">
        </Modal>
    </div>
</template>
<script>
import api from "@/api/commonApi";
import { Avatar } from "view-design";
import code from "@/configs/base.js";
import vueEditor from "@/components/vueEditor";
export default {
    components: {
        Avatar,
        vueEditor
    },
    data() {
        return {
            defaultList: [],
            uploadList: [],
            uploadUrl: api.fileAll,
            jsonObj: { json: '{"urlCode":"'+ code.urlCode.healthEducation +'"}' },
            urlCode: '{"urlCode":"'+ code.urlCode.richText+'"}',
            count: 1,
            maxSize: 1024, //单位kb
            imgName: "",
            visible: false,
            eduInfo: {
                id: null,
                title: null,
                synopsis: null,
                source: null,
                readNum: null,
                pageStyle: null,
                showindex: null,
                enable: 1,
                img: null,
                type: 1,
                content: ""
            },           
            editTt: "",
            id: null,
            pageNo: null,
            tabId: null,
            sonTab: null,
            publicationStatus: null,
            articleText: "",
            tabList: [{ id: 0, name: "全部" }],
            healthEducationSontab: [
                { id: 1, name: "最新" },
                { id: 2, name: "医生忠告" },
                { id: 3, name: "用药" },
                { id: 4, name: "日常" }
            ],
            eduInfoRules: {
                title: [
                    { required: true, message: "标题不能为空", trigger: "blur" }
                ],
                synopsis: [
                    { required: true, message: "概要不能为空", trigger: "blur" }
                ]
            },
            images:'',
        };
    },
    created() {
        let id = parseInt(this.$route.query.id);
        this.tabId = parseInt(this.$route.query.tabId);
        this.pageNo = this.$route.query.pageNo?parseInt(this.$route.query.pageNo):1;
        this.sonTab = this.$route.query.sonTab?parseInt(this.$route.query.sonTab):null;
        this.publicationStatus = this.$route.query.publicationStatus == null?null:parseInt(this.$route.query.publicationStatus);
        this.articleText = this.$route.query.articleText?this.$route.query.articleText:"";
        this.tabList = this.healthEducationSontab;
        if (isNaN(id)) {
            this.editTt = `健康宣教新增`;
        } else {
            this.editTt = `健康宣教编辑`;
            this.id = id;
            this.$axios
                .post(api.findhealArticleById, { id: this.id })
                .then(resp => {
                    if (resp.data.success) {
                        this.eduInfo = resp.data.object;
                        this.eduInfo.enable =this.eduInfo.enable;
                        // this.eduInfo.pageStyle = String(this.eduInfo.pageStyle);
                        this.tryCatch(this.eduInfo.img) &&
                            this.defaultList.push({
                                url:
                                    this.fileBaseUrl +
                                    this.tryCatch(this.eduInfo.img).fileName
                            });
                        this.$nextTick(() => {
                            this.uploadList = this.$refs.upload.fileList;
                        });
                    } else {
                        console.log("查询失败");
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        }

        let breadList = [
            { path: "/index", title: "首页" },
            {
                path: "/index/doctorOperation/medicalConsultation/home",
                title: "医生端运营"
            },
            {
                path: "/index/doctorOperation/medicalConsultation/home",
                title: "健康资讯管理"
            }
        ];
        this.$emit("changeBreadList", breadList);
    },
    mounted() {
        this.uploadList = this.$refs.upload.fileList;
    },
    methods: {
        //优先级限制输入小数
        fictitioussrInput(e) {
            this.eduInfo.showindex=this.eduInfo.showindex.replace(/[^0-9]/g, '')
            if(e.target.value>9999)this.eduInfo.showindex=9999
        },  
        readNumInput(e) {
            this.eduInfo.readNum=this.eduInfo.readNum.replace(/[^0-9]/g, '')
            if(e.target.value>9999999)this.eduInfo.readNum=9999999
        }, 
        afterChange(val) {
            this.eduInfo.content = val;
        },
        submit(name) {
            this.$refs[name].validate(valid => {
                if (valid) {
                    let images = "";
					// 上传
					if (this.images != "") {
						images = this.images;
					} else if (this.uploadList.length) {
						images = this.sourceImages;
						// 默认
					} else {
						images = "";
					}
                    this.eduInfo.img = images;
                    if (
                        this.eduInfo.content != "请输入..." &&
                        this.eduInfo.content != ""
                    ) {
                        let msg = this.id ? "修改成功" : "添加成功";
                        let subApi = this.id
                            ? api.updatehealArticle
                            : api.inserthealArticle;
                        this.eduInfo.content = this.eduInfo.content.replaceAll("<p>&nbsp;</p>","")
                        this.eduInfo.id = this.id && parseInt(this.id);
                        this.eduInfo.enable = this.eduInfo.enable;
                        // this.eduInfo.pageStyle = Number(this.eduInfo.pageStyle)
                        this.eduInfo.showindex = isNaN(
                            parseInt(this.eduInfo.showindex)
                        )
                            ? 1
                            : parseInt(this.eduInfo.showindex);
                            
                        this.$axios
                            .post(subApi, this.eduInfo)
                            .then(resp => {
                                if (resp.data.success) {
                                    this.$Message.success(msg);
                                     //   公用方法
                                    this.functionJS.queryNavgationTo(
                                        this,
                                        "/index/doctorOperation/medicalConsultation/home",
                                        {
                                            tabId: this.tabId,
                                            pageNo: this.pageNo,
                                            sonTab: this.sonTab,
                                            publicationStatus: this.publicationStatus,
                                            articleText: this.articleText
                                        }
                                    );

                                } else {
                                    this.$Message.fail("修改失败，请重试");
                                }
                            })
                            .catch(err => {
                                console.log(err);
                            });
                    } else {
                        this.$Message.error("内容不能为空");
                    }
                } else {
                    this.$Message.error("必填项不能为空");
                }
            });
        },
        reback() {
             //   公用方法
            this.functionJS.queryNavgationTo(
                this,
                "/index/doctorOperation/medicalConsultation/home",
                {
                    tabId: this.tabId, 
                    pageNo: this.pageNo,
                    sonTab: this.sonTab,
                    publicationStatus: this.publicationStatus,
                    articleText: this.articleText
                }
            );

        },
        handleView(name) {
            this.imgName = name;
            this.visible = true;
        },
        handleRemove(file) {
            const fileList = this.$refs.upload.fileList;
            this.$refs.upload.fileList.splice(fileList.indexOf(file), 1);
        },
        handleSuccess(res, file) {
            res = this.uploadFileDecrypt(res);
            if (res.success) {
                console.log("上传成功");
                this.images = JSON.stringify(res.object[0]);
                file.url = this.fileBaseUrl + res.object[0].fileName;
            } else {
                this.alertMsg("网络错误上传失败，请重试");
            }
        },
        handleFormatError(file) {
            this.alertMsg("只支持jpg/jpeg/png格式上传");
        },
        handleMaxSize(file) {
            this.alertMsg(
                `文件${file.name}过大，文件最大限制${this.maxSize}KB`
            );
        },
        handleBeforeUpload() {
            const check = this.uploadList.length < this.count;
            if (!check) {
                this.alertMsg(
                    `最多上传${this.count}张图片,请先点击图片删除老图片`
                );
            }
            return check;
        },
        alertMsg(msg) {
            this.$Message.error({
                render: h => {
                    return h("span", {
                        domProps: {
                            innerHTML: msg
                        },
                        style: { color: "#f00" }
                    });
                },
                duration: 3
            });
        }
    },
};
</script>

<style scoped lang="less">
.edit-news {
    padding: 10px 0;
    width: 100%;
    background: #ffffff;
    box-sizing: border-box;
    .tit {
        margin:10px 0;
        font-weight:bold;
        text-align:center;
    }
    .main{
        width: 98%;
        display: flex;
        flex-direction: column;
        margin: 10px auto;
        border: 1px solid #f0f0f0;
        box-shadow: 0 4px 3px #ebedf8;
        border-radius: 5px;
        margin-bottom: 20px;
        .title {
            font-size: 20px;
            padding-left: 15px;
            margin-bottom: 20px;
            color: #333;
            height: 40px;
            line-height: 40px;
            background: #ebedf8;   
        }      
        .w-select {
            width: 100px;
        }
        .box{
            padding: 0 30px;
        }
    }
    .inputnumber {
        width: 120px;
        height: 30px;
        background: #fff;
        border: none;
        outline: none;
        text-indent: 10px;
        line-height: 30px;
        border: 1px solid #ddd;
        border-radius: 4px;
        color: #666;
    }
    .inputnumber:focus{
        border-color:#5362e1
    }
    .address {
        display: flex;
        flex-direction: row;    
        .left {
            font-size: 14px;
            padding-top: 5px;
            span:last-child {
                margin-right: 5px;
            }
        }
    } 
    .req-icon {
        font-size: 18px;
        color: red;
        display: inline-block;
        height: 18px;
        width: 18px;
        text-align: center;
        line-height: 18px;
        vertical-align: middle;
    }
    .btn{
        width: 100%;
        text-align: center;
        margin-bottom: 10px;
        .button {
            width: 75px;
            height: 35px;
        }
    }
}
</style>
<style lang="less">
.upload-avatar {
    display: inline-block;
    vertical-align: middle;
    width: 64px !important;
    height: 64px !important;
    margin-bottom: 3px;
}
.avatar-box {
    position: relative;
    display: inline-block;
    .avatar-pic {
        width: 64px;
        height: 64px;
    }
    .avatar-img {
        display: none;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(0, 0, 0, 0.6);
        width: 64px;
        height: 64px;
    }
}
.avatar-box:hover .avatar-img {
    display: block;
    text-align: center;
}
.avatar-img i {
    color: #fff;
    font-size: 20px;
    cursor: pointer;
    margin: 0 2px;
    line-height: 64px;
}
.progress {
    width: 64px;
}
</style>